//
//  BookShopCarViewController.m
//  TuDianEducation
//
//  Created by lixinkeji on 2021/1/6.
//  Copyright © 2021 zhangbenchao. All rights reserved.
//


#import "BookShopCarViewController.h"
#import "BookCarConmmitViewController.h"

#import "BkShopCarTableViewCell.h"
#import "BkShopCarBottomView.h"

@interface BookShopCarViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic) NSInteger pageNum;
@property (nonatomic,strong) BkShopCarBottomView *bottomView;
///1结算2删除
@property (nonatomic,strong) NSString *type;

@property (nonatomic,strong) NSMutableArray *selectArray;

@property (nonatomic,strong) NSMutableArray *carAmountArray;


@end

@implementation BookShopCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"购物车";
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = kSubBacColor;
    ///默认结算
    self.type=@"1";
   
    [self addRightNavItemWithTitle:@"完成" color:kGrayTxtColor font:systemFont(TSScaleW(12))];
}
-(void)rigthBtnAction:(id)sender
{
    UIBarButtonItem *item = (UIBarButtonItem *)sender;
    item.title = [item.title isEqualToString:@"完成"]?@"修改":@"完成";
    self.bottomView.type = [item.title isEqualToString:@"完成"]?@"1":@"2";
}

-(NSMutableArray *)selectArray{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}
-(NSMutableArray *)carAmountArray{
    if (!_carAmountArray) {
        _carAmountArray = [NSMutableArray array];
    }
    return _carAmountArray;
}
-(BkShopCarBottomView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[BkShopCarBottomView alloc]init];
        _bottomView.bottom = TSScreenHeight - Height_NavBar - Height_TabBar;
        WS(weakSelf);
        _bottomView.allSelctBlock = ^(BOOL isAllSelct) {
            if (isAllSelct) {
                [weakSelf.selectArray removeAllObjects];
                for (int i = 0; i < self.dataArray.count; i ++) {
                    NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
                    [weakSelf.selectArray addObject:path];
                }
                [weakSelf.tableView reloadData];
                [weakSelf reloadBottomViewData];
            }else{
                [weakSelf.selectArray removeAllObjects];
                [weakSelf.tableView reloadData];
                [weakSelf reloadBottomViewData];
            }
            
        };
        _bottomView.gotoBuyBlock = ^{
            if ([weakSelf gotoBuyArray].count) {
                BookCarConmmitViewController *vc = [[BookCarConmmitViewController alloc]init];
                vc.messageArray = [weakSelf gotoBuyArray];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }else{
                [MBProgressHUD showError:@"请选择商品"];
            }
           
        };
        ///删除购物车
        _bottomView.gotoDeleteBlock = ^{
            if ([weakSelf carsIdArray].count) {
                [weakSelf deletegoodscarWith:[weakSelf carsIdArray]];
            }else{
                [MBProgressHUD showError:@"请选择商品"];
            }
        };
    }
    return _bottomView;
}
-(NSArray *)carsIdArray{
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSIndexPath *path in self.selectArray) {
        NSDictionary *dic = self.dataArray[path.row];
        [resultArray addObject:dic[@"gcid"]];
    }
    return resultArray;;
}
-(NSArray *)gotoBuyArray
{
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSIndexPath *path in self.selectArray) {
        NSDictionary *dic = self.dataArray[path.row];
        [resultArray addObject:dic];
    }
    return resultArray;;
}
-(double)totalMoney
{
    double resultValue = 0.f;
    for (NSDictionary *dic in [self gotoBuyArray]) {
        NSString *newprice = dic[@"newprice"];
        if ([kIsmember intValue] == 0) {
            newprice = dic[@"oldprice"];
        }
        NSString *numbers = dic[@"numbers"];
        resultValue +=newprice.doubleValue*numbers.doubleValue + [dic[@"freight"] doubleValue] *numbers.doubleValue;
    }
    return resultValue;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    if (![self ifNoLoginGotoLoginAction]) {
        return;
    }
    [self headerRefresh];
    self.bottomView.allSelecBtn.selected = NO;
   
}
-(NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, TSScaleW(10), TSScreenWidth, TSScreenHeight - Height_NavBar - TSScaleW(10) -  TSScaleW(55) -Height_TabBar) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       
        if (@available(iOS 11.0, *))
        {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        WS(weakSelf);
        _tableView.mj_header = [CustomGifHeader headerWithRefreshingBlock:^{
                [weakSelf headerRefresh];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [weakSelf footerRefresh];
        }];
    }
    return _tableView;
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BkShopCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MycomendsTableViewCell"];
    if (!cell) {
        cell = [[BkShopCarTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"MycomendsTableViewCell"];
  
    }
    cell.dataDic = self.dataArray[indexPath.row];
    cell.selectBtn.selected = [self.selectArray containsObject:indexPath];
    WS(weakSelf);
    cell.modifyAmountBlock = ^(NSInteger index) {
        NSMutableDictionary *muDic = weakSelf.carAmountArray[indexPath.row];
        NSString *amount = [NSString stringWithFormat:@"%ld",index];
        [muDic setValue:amount forKey:@"numbers"];
        [weakSelf editgoodscarRequstActionWith:muDic];
    };
    cell.selctBlock = ^(BOOL isSelct) {
        [weakSelf selectWithIndex:indexPath];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
}
-(void)selectWithIndex:(NSIndexPath *)indexPath
{
    if ([self.selectArray containsObject:indexPath]) {
        [self.selectArray removeObject:indexPath];
        if (self.bottomView.allSelecBtn.selected) {
            self.bottomView.allSelecBtn.selected= NO;
        }
    }else{
        [self.selectArray addObject:indexPath];
    }
    
    [self.tableView reloadData];
    [self reloadBottomViewData];
}
-(void)reloadBottomViewData
{
    self.bottomView.selectCount = self.selectArray.count;
    self.bottomView.totalLabel.text = [NSString stringWithFormat:@"总计：￥%.2f",[self totalMoney]];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TSScaleW(105);
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectZero];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TSScreenWidth, 0)];
    view.backgroundColor = kMainBgColor;
    return view;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return CGFLOAT_MIN;
}

#pragma mark - 上拉、下拉

-(void)headerRefresh
{
    self.pageNum = 1;
    [self collectListReq];
}

-(void)footerRefresh
{
    [self collectListReq];
}
-(void)collectListReq
{
    NSDictionary *pamas = @{};
   

    [NetWorkTools postConJSONWithUrl:@"getmygoodscar" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        NSArray *array = responseObject[@"dataList"];
        if (result.integerValue == 0) {
           
            [self handleListWithModel:array];
        }else{
             [MBProgressHUD showError:resultNote];
        }

    } fail:^(NSError *error) {

    }];
}

-(void)endRefrash

{
    if (self.tableView.mj_header.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    
    if (self.tableView.mj_footer.state == MJRefreshStateRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
}
-(void)handleListWithModel:(NSArray *)result
{
    
    if (self.pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    if (result.count != kPage_Size) {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }else{
        self.tableView.mj_footer.state = MJRefreshStateIdle;
    }
    
    [self.dataArray addObjectsFromArray:result];
    [self.carAmountArray removeAllObjects];
    for (int i = 0; i < self.dataArray.count; i ++) {
        NSDictionary *dic = self.dataArray[i];
        NSMutableDictionary*mudic = [NSMutableDictionary dictionary];
        [mudic setValue:dic[@"numbers"] forKey:@"numbers"];
        [mudic setValue:dic[@"gcid"] forKey:@"gcid"];
        [self.carAmountArray addObject:mudic];
    }
   
   [SSKJ_NoDataView showNoData:self.dataArray.count toView:self.tableView offY:TSScaleW(10) message:@"还没有数据哦~" imge:[UIImage imageNamed:@"nolikesimg"]];
    
    self.pageNum++;
    
    [self endRefrash];
    
    [self.tableView reloadData];
    [self reloadBottomViewData];
    
}
#pragma mark ---编辑购物车货物数量
///editgoodscar
-(void)editgoodscarRequstActionWith:(NSDictionary *)pamas
{
    [NetWorkTools postConJSONWithUrl:@"editgoodscar" parameters:pamas success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        if (result.integerValue == 0) {
           
            [self headerRefresh];
        }else{
             
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {

    }];
}
#pragma mark ---删除购物车
-(void)deletegoodscarWith:(NSArray *)array
{
    NSDictionary *pams = @{@"gcidlist":array};
    [NetWorkTools postConJSONWithUrl:@"deletegoodscar" parameters:pams success:^(id responseObject) {
        NSString *result = responseObject[@"result"];
        NSString *resultNote = responseObject[@"resultNote"];
        if (result.integerValue == 0) {
            [self headerRefresh];
        }else{
             
        }
        [MBProgressHUD showError:resultNote];
    } fail:^(NSError *error) {

    }];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.selectArray removeAllObjects];
    
}
@end
